/**
 * 原型修改方式，针对个别不喜欢用logger封装方式的特殊处理
 */
if (process.env.NODE_ENV !== 'production') {
    if (window.console && console.log) {
        let ts = function () {};
        ts.toString = function () {
            return '[' + formatTime(new Date(), 'mm:ss ms') + ']' + '[' + document.location.pathname + '] ';
        };
        ['info', 'log', 'warn', 'error'].forEach(method => {
            console[method] = console[method].bind(console, '%s', ts);
        });
    } else {
        ['info', 'log', 'warn', 'error'].forEach(method => {
            console[method] = () => {};
        });
    }
}

export function formatTime(time, format) {
    if (!time) {
        return '';
    }
    if (typeof time === 'string') {
        time = time.toString().replace(/-/g, '/'); // ios下new Date(2016-10-31)报错:invalid date...要改为: 2016/10/31样式
    }
    if (typeof time === 'number' && time.toString().length === 10) {
        time = parseInt(time + '000');
    }

    // 过去
    let stamp = new Date(time),
        cur = new Date(),
        year = stamp.getFullYear(),
        month = stamp.getMonth() + 1 > 9 ? stamp.getMonth() + 1 : '0' + (stamp.getMonth() + 1),
        day = stamp.getDate() > 9 ? stamp.getDate() : '0' + stamp.getDate(),
        hour = stamp.getHours() > 9 ? stamp.getHours() : '0' + stamp.getHours(),
        minute = stamp.getMinutes() > 9 ? stamp.getMinutes() : '0' + stamp.getMinutes(),
        sec = stamp.getSeconds() > 9 ? stamp.getSeconds() : '0' + stamp.getSeconds(),
        ms =
            stamp.getMilliseconds() < 100
                ? '0' + (stamp.getMilliseconds() < 10 ? '0' + stamp.getMilliseconds() : stamp.getMilliseconds())
                : stamp.getMilliseconds(),
        weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
        week = weeks[stamp.getDay()];
    if (!year) {
        return '0000年00月00日';
    }

    if (format) {
        format = format.replace('yyyy', year);
        format = format.replace('MM', month);
        format = format.replace('dd', day);
        format = format.replace('hh', hour);
        format = format.replace('mm', minute);
        format = format.replace('ss', sec);
        format = format.replace('ms', ms);

        if (year === cur.getFullYear() && stamp.getMonth() === cur.getMonth() && stamp.getDate() === cur.getDate()) {
            week = '今天';
        }
        format = format.replace('week', week);
    } else {
        format = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
    }

    return format;
}

const MIN_NUMBER = -Number.MAX_VALUE,
    MAX_NUMBER = Number.MAX_VALUE;

export function getCurrentMapDimensions(leftBottomP, rightTopP, dimensions, ratio = 1) {
    if (!leftBottomP) leftBottomP = [];
    if (!rightTopP) rightTopP = [];
    let xMin = dimensions ? dimensions[0] : leftBottomP.length ? MAX_NUMBER : -10000,
        xMax = dimensions ? dimensions[1] : rightTopP.length ? MIN_NUMBER : +10000,
        yMin = dimensions ? dimensions[2] : leftBottomP.length ? MAX_NUMBER : -10000,
        yMax = dimensions ? dimensions[3] : rightTopP.length ? MIN_NUMBER : +10000;

    if (!leftBottomP.x || !leftBottomP.y || !rightTopP.x || !rightTopP.y) return [xMin, xMax, yMin, yMax];
    xMin = leftBottomP.x;
    xMax = rightTopP.x;
    yMin = leftBottomP.y;
    yMax = rightTopP.y;
    ratio = 1; // todo: del ratio
    return [xMin * ratio, xMax * ratio, yMin * ratio, yMax * ratio];
}

export function getVehicleDimensions(model, vehicles = [], dimensions, ratio = 1) {
    if (!vehicles) vehicles = [];
    let xMin = dimensions ? dimensions[0] : vehicles.length ? MAX_NUMBER : -10000,
        xMax = dimensions ? dimensions[1] : vehicles.length ? MIN_NUMBER : +10000,
        yMin = dimensions ? dimensions[2] : vehicles.length ? MAX_NUMBER : -10000,
        yMax = dimensions ? dimensions[3] : vehicles.length ? MIN_NUMBER : +10000;

    if (!model) return [xMin, xMax, yMin, yMax];
    let r = Math.max(model.size.x, model.size.y) * 0.75;

    for (let i = 0; i < vehicles.length; i++) {
        let t = vehicles[i];
        if (t.tunedPos && t.tunedPos.x - r < xMin) xMin = t.tunedPos.x - r;
        if (t.tunedPos && t.tunedPos.x + r > xMax) xMax = t.tunedPos.x + r;
        if (t.tunedPos && t.tunedPos.y - r < yMin) yMin = t.tunedPos.y - r;
        if (t.tunedPos && t.tunedPos.y + r > yMax) yMax = t.tunedPos.y + r;
    }
    ratio = 1; // todo: del ratio
    return [xMin * ratio, xMax * ratio, yMin * ratio, yMax * ratio];
}

export function getPathDimensions(paths = [], dimensions, ratio = 1) {
    if (!paths) paths = [];
    let xMin = dimensions ? dimensions[0] : paths && paths.length ? MAX_NUMBER : -10000,
        xMax = dimensions ? dimensions[1] : paths && paths.length ? MIN_NUMBER : +10000,
        yMin = dimensions ? dimensions[2] : paths && paths.length ? MAX_NUMBER : -10000,
        yMax = dimensions ? dimensions[3] : paths && paths.length ? MIN_NUMBER : +10000;

    for (let i = 0; i < paths.length; i++) {
        let path = paths[i];
        // var sp = path.startPoint();
        // var ep = path.endPoint();
        let sp = path.controlPoints ? path.controlPoints[0] : null;
        let ep = path.controlPoints ? path.controlPoints[path.controlPoints.length - 1] : null;
        if (!sp || !ep) return [xMin, xMax, yMin, yMax];

        if (sp.x < xMin) xMin = sp.x;
        if (sp.x > xMax) xMax = sp.x;
        if (sp.y < yMin) yMin = sp.y;
        if (sp.y > yMax) yMax = sp.y;

        if (ep.x < xMin) xMin = ep.x;
        if (ep.x > xMax) xMax = ep.x;
        if (ep.y < yMin) yMin = ep.y;
        if (ep.y > yMax) yMax = ep.y;
    }
    ratio = 1; // todo: del ratio
    return [xMin * ratio, xMax * ratio, yMin * ratio, yMax * ratio];
}
export function getContourDimensions(contours = [], dimensions, ratio = 1) {
    if (!contours) contours = [];
    let xMin = dimensions ? dimensions[0] : contours.length ? MAX_NUMBER : -10000,
        xMax = dimensions ? dimensions[1] : contours.length ? MIN_NUMBER : +10000,
        yMin = dimensions ? dimensions[2] : contours.length ? MAX_NUMBER : -10000,
        yMax = dimensions ? dimensions[3] : contours.length ? MIN_NUMBER : +10000;

    if (!contours || !contours.length) return [xMin, xMax, yMin, yMax];
    for (var i = 0; i < contours.length; i++) {
        if (!contours[i] || !contours[i].points || !contours[i].points.length) continue;
        for (var k = 0; k < contours[i].points.length; k++) {
            var p = contours[i].points[k];

            if (p.x < xMin) xMin = p.x;
            if (p.x > xMax) xMax = p.x;
            if (p.y < yMin) yMin = p.y;
            if (p.y > yMax) yMax = p.y;
        }
    }
    ratio = 1; // todo: del ratio
    return [xMin * ratio, xMax * ratio, yMin * ratio, yMax * ratio];
}

export function thumb(url, { width = 750, height = 0 } = {}) {
    let str = url;
    // console.log('utils.thumb: ', url, width, height);
    // return url + '!/fw/100';
    if (/upaiyun.com/.test(url) || /upyun-img/.test(url)) {
        // 又拍云缩略图
        if (width && height) str += '!/both/' + width + 'x' + height;
        else if (width) str += '!/fw/' + width;
        else if (height) str += '!/fh/' + height;
    } else if (/static.91wuliu.com|aliyuncs.com/.test(url)) {
        // 阿里云缩略图
        if (width && height) str += '?x-oss-process=image/resize,m_fill,h_' + height + ',w_' + width;
        else if (width) str += '?x-oss-process=image/resize,w_' + width;
        else if (height) str += '?x-oss-process=image/resize,h_' + height;
    } else if (/static.91wuliu.com|aliyuncs.com/.test(url)) {
        if (width && height) str += '?x-oss-process=image/resize,m_fill,h_' + height + ',w_' + width;
        else if (width) str += '?x-oss-process=image/resize,w_' + width;
        else if (height) str += '?x-oss-process=image/resize,h_' + height;
    }
    return str;
}

export function getSessionStorage(key = '') {
    let storage = window.sessionStorage,
        _uid = key || window.location.host.split('.').reverse().join('.');

    if (!storage) {
        console.error('This browser does NOT support sessionStorage!');
        return;
    }

    if (!storage[_uid]) {
        var obj = {};
        storage[_uid] = JSON.stringify(obj);
    }

    return {
        set: function (key, value) {
            // 设置某个已保存的键值
            var obj = JSON.parse(storage.getItem(_uid));
            obj[key] = value;
            storage[_uid] = JSON.stringify(obj);
        },
        get: function (key) {
            // 获取某个已保存的键值
            if (!this.has()) return '';
            var obj = JSON.parse(storage.getItem(_uid));
            if (obj.hasOwnProperty(key)) {
                return obj[key];
            }
            return '';
        },
        has: function () {
            var v = storage.getItem(_uid);
            var obj = JSON.parse(v);
            if (typeof obj !== 'object' || obj == null) {
                return false;
            }
            return true;
        },
        remove: function (key) {
            storage.removeItem(key);
        },
        clear: function () {
            storage.clear();
        }
    };
}

export function getLocalStorage(key = '') {
    let storage = window.localStorage,
        _uid = key || window.location.host.split('.').reverse().join('.');

    if (!storage) {
        console.error('This browser does NOT support localStorage!');
        return;
    }

    if (!storage[_uid]) {
        var obj = {};
        storage[_uid] = JSON.stringify(obj);
    }

    return {
        set: function (key, value) {
            // 设置某个已保存的键值
            var obj = JSON.parse(storage.getItem(_uid));
            obj[key] = value;
            storage[_uid] = JSON.stringify(obj);
        },
        get: function (key) {
            // 获取某个已保存的键值
            if (!this.has()) return;
            var obj = JSON.parse(storage.getItem(_uid));
            if (obj.hasOwnProperty(key)) {
                return obj[key];
            }
            return null;
        },
        has: function () {
            var v = storage.getItem(_uid);
            var obj = JSON.parse(v);
            if (typeof obj !== 'object' || obj == null) {
                return false;
            }
            return true;
        },
        remove: function (key) {
            storage.removeItem(key);
        },
        clear: function () {
            storage.clear();
        }
    };
}
